package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.entity.AlarmRecord;
import com.example.shutdown_v1.repository.AlarmRecordRepository;
import com.example.shutdown_v1.service.AlarmService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 告警查询API
 */
@Slf4j
@RestController
@RequestMapping("/api/alarm")
@RequiredArgsConstructor
public class AlarmController {

    private final AlarmRecordRepository alarmRecordRepository;
    private final AlarmService alarmService;

    /**
     * 查询告警列表
     * GET /api/alarm/list?shopId={shopId}&confirmed={confirmed}
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> listAlarms(
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) Boolean confirmed) {
        
        List<AlarmRecord> alarms;
        
        if (shopId != null && confirmed != null) {
            alarms = alarmRecordRepository.findByShopIdAndConfirmedOrderByAlarmTimeDesc(shopId, confirmed);
        } else if (shopId != null) {
            alarms = alarmRecordRepository.findByShopIdAndAlarmTimeBetween(
                    shopId, LocalDateTime.now().minusDays(30), LocalDateTime.now());
        } else if (confirmed != null) {
            alarms = alarmRecordRepository.findByConfirmedOrderByAlarmTimeDesc(confirmed);
        } else {
            alarms = alarmRecordRepository.findAll();
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("alarms", alarms);
        response.put("count", alarms.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 查询未确认告警
     * GET /api/alarm/unconfirmed
     */
    @GetMapping("/unconfirmed")
    public ResponseEntity<Map<String, Object>> getUnconfirmedAlarms() {
        List<AlarmRecord> alarms = alarmRecordRepository.findByConfirmedOrderByAlarmTimeDesc(false);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("alarms", alarms);
        response.put("count", alarms.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 查询指定时间范围的告警
     * GET /api/alarm/range?shopId={shopId}&start={start}&end={end}
     */
    @GetMapping("/range")
    public ResponseEntity<Map<String, Object>> getAlarmsByTimeRange(
            @RequestParam Long shopId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        
        List<AlarmRecord> alarms = alarmRecordRepository.findByShopIdAndAlarmTimeBetween(shopId, start, end);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("shopId", shopId);
        response.put("startTime", start);
        response.put("endTime", end);
        response.put("alarms", alarms);
        response.put("count", alarms.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 确认告警
     * POST /api/alarm/confirm/{alarmId}
     */
    @PostMapping("/confirm/{alarmId}")
    public ResponseEntity<Map<String, Object>> confirmAlarm(
            @PathVariable Long alarmId,
            @RequestBody ConfirmRequest request) {
        
        Map<String, Object> response = new HashMap<>();
        
        boolean success = alarmService.confirmAlarm(alarmId, request.getConfirmedBy());
        
        if (success) {
            response.put("success", true);
            response.put("message", "告警已确认");
        } else {
            response.put("success", false);
            response.put("message", "告警不存在");
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 查询告警详情
     * GET /api/alarm/detail/{alarmId}
     */
    @GetMapping("/detail/{alarmId}")
    public ResponseEntity<Map<String, Object>> getAlarmDetail(@PathVariable Long alarmId) {
        var alarmOpt = alarmRecordRepository.findById(alarmId);
        
        Map<String, Object> response = new HashMap<>();
        
        if (alarmOpt.isEmpty()) {
            response.put("success", false);
            response.put("message", "告警不存在");
            return ResponseEntity.notFound().build();
        }
        
        response.put("success", true);
        response.put("alarm", alarmOpt.get());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 请求体：确认告警
     */
    @lombok.Data
    public static class ConfirmRequest {
        private String confirmedBy;
    }
}

